package com.metaera.app.controller.view;

import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.metaera.app.R;
import com.metaera.app.controller.presenter.SearchHistoryPresenter;
import com.metaera.app.controller.view.core.INetworkRequestView;


import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class SearchHistoryListView implements INetworkRequestView<List<String>> {

    private final ViewGroup mHistorySearchLayout;

    private final SearchHistoryListView.Adapter mSearchHistoryAdapter;

    public SearchHistoryListView(View rootView, SearchHistoryPresenter presenter) {
        RecyclerView recyclerView = rootView.findViewById(R.id.history_recycler_view);
        mHistorySearchLayout = rootView.findViewById(R.id.rl_history_search);

        EditText etSearch = rootView.findViewById(R.id.et_search);
        Button buttonSearch = rootView.findViewById(R.id.button_search);

        mSearchHistoryAdapter = new SearchHistoryListView.Adapter(presenter);
        recyclerView.setAdapter(mSearchHistoryAdapter);

        mSearchHistoryAdapter.setOnItemClickListener((adapter, view, position) -> {
            String keyword = mSearchHistoryAdapter.getItem(position);
            etSearch.setText(keyword);
            etSearch.setSelection(keyword.length());
            buttonSearch.performClick();
        });
    }

    @Override
    public void successful(List<String> data) {
        mSearchHistoryAdapter.setList(data);
        mHistorySearchLayout.setVisibility(data.isEmpty() ? View.GONE : View.VISIBLE);
    }


    public static class Adapter extends BaseQuickAdapter<String, BaseViewHolder> {

        private final SearchHistoryPresenter mPresenter;

        public Adapter(SearchHistoryPresenter presenter) {
            super(R.layout.item_search_history);
            mPresenter = presenter;
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, String item) {
            holder.setText(R.id.tv_history_name, item);
            holder.getView(R.id.but_delete).setOnClickListener(v -> mPresenter.remove(item));
        }
    }

}
